package local.xinshi.netmgr.pkg;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

public class WebSessions {
    private static final ConcurrentHashMap<String, WebSocketSession> webSessions = new ConcurrentHashMap<>();
    private static Logger logger = LoggerFactory.getLogger(WebSessions.class);

    /**
     * 将 httpsessionID 和对应的 websocketSession 添加为映射
     * @param key HttpSessionID
     * @param value websocketSession
     */
    public static void put(String key, WebSocketSession value) {
        webSessions.put(key, value);
    }

    /**
     * 删除指定 httpsessionID 的 websocketSession
     * @param key 指定的 httpsessionID
     */
    public static WebSocketSession del(String key) {
        return webSessions.remove(key);
    }

    /**
     * 向所有在线用户广播消息
     * @param msg 要广播的消息
     * @param excludeToken 不广播的 httpsessionID (一般是发送了更改请求的会话) null或""则向所有会话广播
     */
    public static void broad(String msg,String excludeToken) {
        WebSocketSession excludeSession = webSessions.get(excludeToken==null?"":excludeToken);
        for (WebSocketSession session : webSessions.values()) {
            if(session == excludeSession) continue;
            try {
                session.sendMessage(new TextMessage(msg));
            } catch (IOException e) {
                logger.info(e.getMessage());
            }
        }
    }

}